package com.ptc.ims.client;

import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.HasWidgets;
import com.ptc.ims.client.event.CancelCreateEditProductEvent;
import com.ptc.ims.client.event.CancelCreateEditProductEventHandler;
import com.ptc.ims.client.event.CreateProductEvent;
import com.ptc.ims.client.event.CreateProductEventHandler;
import com.ptc.ims.client.event.EditProductEvent;
import com.ptc.ims.client.event.EditProductEventHandler;
import com.ptc.ims.client.presenter.Presenter;
import com.ptc.ims.client.presenter.ProductPresenterFactory;

/**
 * Page history handler
 * @author Gelo
 *
 */
public class AppController 
implements ValueChangeHandler<String> 
{
	private final HandlerManager eventBus;
	private final InventoryServiceAsync rpcService; 
	private HasWidgets container;

	public AppController(HandlerManager eventBus, InventoryServiceAsync rpcService) 
	{
		this.eventBus = eventBus;
		this.rpcService = rpcService;
		bind();
	}

	@Override
	public void onValueChange(ValueChangeEvent<String> event) 
	{
		String token = event.getValue();
		Presenter presenter = ProductPresenterFactory.createPresenter(token, rpcService, eventBus);
		
		if (presenter != null)
		{
			presenter.go(container);
		}		
	}

	public void go(final HasWidgets container) 
	{
		this.container = container;
		if ("".equals(History.getToken())) 
		{
			History.newItem("list");
		}
		else
		{
			History.fireCurrentHistoryState();
		}
	}

	private void bind()
	{
		History.addValueChangeHandler(this);
		
		eventBus.addHandler(CreateProductEvent.TYPE, new CreateProductEventHandler() {			
			@Override
			public void onCreateProduct(CreateProductEvent event) 
			{
				History.newItem("create");				
			}
		});
		eventBus.addHandler(EditProductEvent.TYPE, new EditProductEventHandler() {			
			@Override
			public void onEditProduct(EditProductEvent event)
			{
				String token = "edit&productId=" + event.getProductId();
				History.newItem(token);
			}
		});
		eventBus.addHandler(CancelCreateEditProductEvent.TYPE, new CancelCreateEditProductEventHandler() {			
			@Override
			public void onCancelCreate(CancelCreateEditProductEvent event)
			{
				History.newItem("list");		
			}
		});
	}

}
